#include "serverconnector.h"
#include "./tools/data/encryptor.h"

ServerConnector ServerConnector::m_instance;
ServerConnector& ServerConnector::getInstance()
{
    return m_instance;
}

ServerConnector::ServerConnector(QObject *parent)
    :QObject{parent}
{
    m_socket = new QTcpSocket(this);

    // 监听连接状态变化
    connect(m_socket, &QTcpSocket::connected, this, &ServerConnector::onConnected);
    connect(m_socket, &QTcpSocket::errorOccurred, this, &ServerConnector::onErrorOccurred);
    connect(m_socket, &QTcpSocket::readyRead, this, &ServerConnector::onDataReceived);
    connect(m_socket, &QTcpSocket::disconnected, this, &ServerConnector::onDisconnected);
}

ServerConnector::~ServerConnector()
{

}

void ServerConnector::connectToServer()
{
    // 连接服务器
    m_socket->connectToHost("127.0.0.1", 8080);  // 连接到服务器的 IP 和端口

}

void ServerConnector::onConnected()
{
    // qDebug() << "连接成功";
    QString tip = "连接成功";
    emit ConnectionStatusChanged(true, tip);
}

void ServerConnector::onErrorOccurred(QAbstractSocket::SocketError socketError)
{
    // qDebug() << "连接失败";
    QString tip = "连接失败";
    switch (socketError) {
    case QAbstractSocket::ConnectionRefusedError:
        // qDebug() << "Connection was refused. The server might not be running.";
        tip = "连接被拒绝，检查服务器运行状态";
        break;
    case QAbstractSocket::HostNotFoundError:
        // qDebug() << "Host not found. Please check the IP address or domain.";
        tip = "无法找到主机";
        break;
    case QAbstractSocket::SocketTimeoutError:
        // qDebug() << "Connection timed out.";
        tip = "连接超时";
        break;
    default:
        // qDebug() << "An unknown error occurred: " << socketError;
        tip = "未知错误";
        break;
    }
    emit ConnectionStatusChanged(false, tip);
}

void ServerConnector::onDataReceived()
{
    // qDebug() << "收到服务器回应";
    QByteArray originData = m_socket->readAll();
    QByteArray decryptedData = Encryptor::decrypt(originData);
    emit sendOriginData(decryptedData);
}

void ServerConnector::onDisconnected()
{
    // qDebug() << "断开连接";
    QString tip = "断开连接";
    emit ConnectionStatusChanged(false, tip);

}

void ServerConnector::sendData(const QByteArray data)
{
    QByteArray encryptedData = Encryptor::encrypt(data);
    m_socket->write(encryptedData);
    m_socket->flush();  // 立即发送数据
    qDebug() << "发送成功";
}

